package com.kfpanda.search.index;

import java.io.File;
import java.io.IOException;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.LockObtainFailedException;
import org.springframework.stereotype.Repository;
import org.wltea.analyzer.lucene.IKAnalyzer;

@Repository("indexerImpl")
public class IndexerImpl implements Indexer{
	private Logger logger = Logger.getLogger(IndexerImpl.class);
	
	protected Analyzer analyzer = new IKAnalyzer();// 采用的分词器
	protected String indexSaveDir;
	protected IndexWriter writer;
	
	@SuppressWarnings("deprecation")
	public IndexWriter createWriter(){
		if(this.writer != null){
			return this.writer;
		}
		//第三个参数 为true表示新建，false表示添加到原有索引中
		try {
			this.writer = new IndexWriter(FSDirectory.open(new File(indexSaveDir)),
					analyzer, true,
					IndexWriter.MaxFieldLength.LIMITED);
		} catch (CorruptIndexException e) {
			logger.debug(e);
		} catch (LockObtainFailedException e) {
			logger.debug(e);
		} catch (IOException e) {
			logger.debug(e);
		}
		return this.writer;
	}
	
	@Override
	public void indexCreate(String indexSaveDir, Document document)
			throws CorruptIndexException, IOException {
		if(StringUtils.isNotBlank(indexSaveDir)){
			this.indexSaveDir = indexSaveDir;
		}
		this.createWriter();
		this.writer.addDocument(document);
	}
	
	@Override
	public void indexCreate(IndexWriter writer, Document document)
			throws CorruptIndexException, IOException {
		if(writer == null){
			this.createWriter();
		}
		this.writer.addDocument(document);
	}

	public Analyzer getAnalyzer() {
		return analyzer;
	}

	public void setAnalyzer(Analyzer analyzer) {
		this.analyzer = analyzer;
	}

	public String getIndexSaveDir() {
		return indexSaveDir;
	}

	public void setIndexSaveDir(String indexSaveDir) {
		this.indexSaveDir = indexSaveDir;
	}

	public IndexWriter getWriter() {
		return writer;
	}

	public void setWriter(IndexWriter writer) {
		this.writer = writer;
	}

}
